package com.kkb.robotcustomerservice.controller;

import com.alibaba.excel.EasyExcel;
import com.kkb.robotcustomerservice.entities.KnowledgeBase;
import com.kkb.robotcustomerservice.service.impl.KnowledgeBaseServiceImpl;
import com.kkb.robotcustomerservice.util.ExcelListener;
import com.kkb.robotcustomerservice.util.ResponseResult;
import com.kkb.robotcustomerservice.util.User;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@CrossOrigin
public class DownloadExcelController {

    @Autowired
    private KnowledgeBaseServiceImpl knowledgeBaseService;

    /**
     * @author 0715-YuHao
     * @description 问题模板下载
     * @date 11:23 2020/11/20
     **/
    @GetMapping("/downloadExcel")
    public ResponseEntity<byte[]> downExcel() throws IOException {

        Resource resource = new ClassPathResource("static\\questionTemplate\\批量导入问题模板.xlsx");
        File file = resource.getFile();

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        httpHeaders.setContentDispositionFormData("attachment", URLEncoder.encode("批量导入问题模板.xlsx", "UTF-8"));
        return new ResponseEntity<>(FileUtils.readFileToByteArray(file), httpHeaders, HttpStatus.CREATED);
    }

    /**
     * @author 0715-DengJinxi
     * @description 问题模板上传
     * @date 11:23 2020/11/25
     **/
    @PostMapping("/uploadExcel")
    public ResponseResult uploadExcel(@RequestParam("file") MultipartFile file, User user){
        try {
            EasyExcel.read(file.getInputStream(), KnowledgeBase.class,new ExcelListener(knowledgeBaseService,user)).sheet().doRead();
        } catch (IOException e) {
            return ResponseResult.error("上传失败");
        }
        return ResponseResult.error("上传成功");
    }

}
